{% extends "pc/template.html" %}

{% block title %}平台管理 - BlackWidow{% endblock %}

{% include 'pc/公共样式配置/CSS总样式.html' %}

{% block css %}
<style>
    .platform-container {
        padding: 2rem;
    }
    .platform-header {
        margin-bottom: 2rem;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }
    .platform-title {
        color: #566a7f;
        margin-bottom: 0.5rem;
    }
    .platform-subtitle {
        color: #697a8d;
    }
    .platform-logo {
        width: 40px;
        height: 40px;
        object-fit: contain;
    }
    .description-cell {
        max-width: 300px;
        position: relative;
    }
    .description-text {
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }
    .description-full {
        display: none;
        position: absolute;
        left: 0;
        top: 100%;
        background: white;
        padding: 0.5rem;
        border-radius: 0.25rem;
        box-shadow: 0 2px 8px rgba(0,0,0,0.15);
        z-index: 1000;
        min-width: 300px;
        max-width: 400px;
        white-space: normal;
    }
    .description-cell:hover .description-full {
        display: block;
    }
    .table th {
        background-color: #f8f9fa;
        font-weight: 600;
    }
    .pagination {
        margin-top: 1rem;
        justify-content: center;
    }
    .page-size-selector {
        width: 100px;
    }
    .table-container {
        background: white;
        border-radius: 0.5rem;
        box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
    }
    .logo-preview {
        width: 100px;
        height: 100px;
        object-fit: contain;
        border: 1px dashed #d9dee3;
        border-radius: 0.25rem;
        padding: 0.5rem;
        margin-top: 0.5rem;
    }
    .action-buttons {
        display: flex;
        gap: 0.5rem;
    }
    .btn-action {
        color: #566a7f;
        background: none;
        border: none;
        padding: 0.25rem 0.5rem;
        cursor: pointer;
        transition: color 0.2s;
    }
    .btn-action:hover {
        color: #696cff;
    }
    .dropdown-menu {
        min-width: 120px;
    }
    .dropdown-item {
        display: flex;
        align-items: center;
        gap: 0.5rem;
        padding: 0.5rem 1rem;
    }
    .dropdown-item i {
        font-size: 1.1rem;
    }
    .dropdown-item.text-danger {
        color: #dc3545 !important;
    }
    .dropdown-item.text-danger:hover {
        background-color: #dc3545;
        color: white !important;
    }
</style>
{% endblock %}

{% block content %}
<div class="platform-container">
    <div class="platform-header">
        <div>
            <h2 class="platform-title">平台管理</h2>
            <p class="platform-subtitle">查看和管理所有接入的平台信息</p>
        </div>
        <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addPlatformModal">
            <i class="iconfont icon-jia"></i> 添加平台
        </button>
    </div>

    <div class="table-container">
        <div class="table-responsive">
            <table class="table table-hover">
                <thead>
                    <tr>
                        <th style="width: 60px">Logo</th>
                        <th style="width: 150px">平台名称</th>
                        <th>描述</th>
                        <th style="width: 180px">创建时间</th>
                        <th style="width: 180px">更新时间</th>
                        <th style="width: 280px">平台ID</th>
                        <th style="width: 80px">操作</th>
                    </tr>
                </thead>
                <tbody id="platformTableBody">
                    <!-- 表格内容将通过 JavaScript 动态加载 -->
                </tbody>
            </table>
        </div>
        
        <div class="d-flex justify-content-between align-items-center p-3 border-top">
            <div class="d-flex align-items-center">
                <span class="me-2">每页显示:</span>
                <select class="form-select form-select-sm page-size-selector" id="pageSize">
                    <option value="10">10</option>
                    <option value="20">20</option>
                    <option value="50">50</option>
                    <option value="100">100</option>
                </select>
            </div>
            <nav aria-label="Page navigation">
                <ul class="pagination mb-0" id="pagination">
                    <!-- 分页将通过 JavaScript 动态加载 -->
                </ul>
            </nav>
        </div>
    </div>
</div>

<!-- 添加平台模态框 -->
<div class="modal fade" id="addPlatformModal" tabindex="-1" aria-labelledby="addPlatformModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="addPlatformModalLabel">添加平台</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="addPlatformForm">
                    <div class="mb-3">
                        <label for="platformName" class="form-label">平台名称</label>
                        <input type="text" class="form-control" id="platformName" required>
                    </div>
                    <div class="mb-3">
                        <label for="platformLogo" class="form-label">平台Logo</label>
                        <input type="file" class="form-control" id="platformLogo" accept="image/*">
                        <img id="logoPreview" class="logo-preview d-none" alt="Logo预览">
                        <input type="hidden" id="logoUrl">
                    </div>
                    <div class="mb-3">
                        <label for="platformDescription" class="form-label">平台描述</label>
                        <textarea class="form-control" id="platformDescription" rows="4" required></textarea>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="submitPlatform">确定</button>
            </div>
        </div>
    </div>
</div>

<!-- 删除确认模态框 -->
<div class="modal fade" id="deleteConfirmModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">确认删除</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <p>确定要删除这个平台吗？此操作不可恢复。</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-danger" id="confirmDelete">确定删除</button>
            </div>
        </div>
    </div>
</div>

<!-- 更新平台模态框 -->
<div class="modal fade" id="updatePlatformModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">更新平台</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="updatePlatformForm">
                    <input type="hidden" id="updatePlatformId">
                    <div class="mb-3">
                        <label for="updatePlatformName" class="form-label">平台名称</label>
                        <input type="text" class="form-control" id="updatePlatformName" required>
                    </div>
                    <div class="mb-3">
                        <label for="updatePlatformLogo" class="form-label">平台Logo</label>
                        <input type="file" class="form-control" id="updatePlatformLogo" accept="image/*">
                        <img id="updateLogoPreview" class="logo-preview d-none" alt="Logo预览">
                        <input type="hidden" id="updateLogoUrl">
                    </div>
                    <div class="mb-3">
                        <label for="updatePlatformDescription" class="form-label">平台描述</label>
                        <textarea class="form-control" id="updatePlatformDescription" rows="4" required></textarea>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="submitUpdate">确定</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block js %}
<script>
let allPlatforms = [];
let currentPage = 1;
let pageSize = 10;
let platformToDelete = null;

// 获取所有平台信息
function getAllPlatforms() {
    axios.post('/api/platform_info/v1/get/all_platform/')
        .then(response => {
            if (response.data.code === 0) {
                allPlatforms = response.data.data;
                renderTable();
                renderPagination();
            } else {
                showToast(response.data.message, 'error');
            }
        })
        .catch(error => {
            console.error('获取平台信息失败:', error);
            showToast('获取平台信息失败', 'error');
        });
}

// 渲染表格
function renderTable() {
    const start = (currentPage - 1) * pageSize;
    const end = start + pageSize;
    const pageData = allPlatforms.slice(start, end);
    
    const tbody = document.getElementById('platformTableBody');
    tbody.innerHTML = '';
    
    pageData.forEach(platform => {
        const tr = document.createElement('tr');
        tr.innerHTML = `
            <td><img src="${platform.logo}" alt="${platform.name}" class="platform-logo"></td>
            <td>${platform.name}</td>
            <td class="description-cell">
                <div class="description-text">${platform.description}</div>
                <div class="description-full">${platform.description}</div>
            </td>
            <td>${platform.create_time}</td>
            <td>${platform.update_time}</td>
            <td><small class="text-muted">${platform.platform_id}</small></td>
            <td>
                <div class="dropdown">
                    <button class="btn-action" type="button" data-bs-toggle="dropdown" aria-expanded="false">
                        <i class="bx bx-dots-vertical-rounded"></i>
                    </button>
                    <ul class="dropdown-menu">
                        <li>
                            <a class="dropdown-item" href="#" onclick="showUpdateModal('${platform.platform_id}', '${platform.name}', '${platform.description}')">
                                <i class="bx bx-edit"></i>
                                <span>编辑</span>
                            </a>
                        </li>
                        <li>
                            <a class="dropdown-item text-danger" href="#" onclick="showDeleteConfirm('${platform.platform_id}')">
                                <i class="bx bx-trash"></i>
                                <span>删除</span>
                            </a>
                        </li>
                    </ul>
                </div>
            </td>
        `;
        tbody.appendChild(tr);
    });
}

// 显示删除确认对话框
function showDeleteConfirm(platformId) {
    platformToDelete = platformId;
    const modal = new bootstrap.Modal(document.getElementById('deleteConfirmModal'));
    modal.show();
}

// 确认删除
document.getElementById('confirmDelete').addEventListener('click', function() {
    if (!platformToDelete) return;

    const formData = new FormData();
    formData.append('PlatformInfoID', platformToDelete);

    axios.post('/api/platform_info/v1/delete/', formData, {
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        }
    })
    .then(response => {
        if (response.data.code === 0) {
            showToast('删除平台成功', 'success');
            // 关闭模态框
            const modal = bootstrap.Modal.getInstance(document.getElementById('deleteConfirmModal'));
            modal.hide();
            // 刷新平台列表
            getAllPlatforms();
        } else {
            showToast(response.data.message, 'error');
        }
    })
    .catch(error => {
        console.error('删除平台失败:', error);
        showToast('删除平台失败', 'error');
    })
    .finally(() => {
        platformToDelete = null;
    });
});

// 渲染分页
function renderPagination() {
    const totalPages = Math.ceil(allPlatforms.length / pageSize);
    const pagination = document.getElementById('pagination');
    pagination.innerHTML = '';
    
    // 上一页
    pagination.innerHTML += `
        <li class="page-item ${currentPage === 1 ? 'disabled' : ''}">
            <a class="page-link" href="#" data-page="${currentPage - 1}">上一页</a>
        </li>
    `;
    
    // 页码
    for (let i = 1; i <= totalPages; i++) {
        if (
            i === 1 || // 第一页
            i === totalPages || // 最后一页
            (i >= currentPage - 2 && i <= currentPage + 2) // 当前页附近的页码
        ) {
            pagination.innerHTML += `
                <li class="page-item ${i === currentPage ? 'active' : ''}">
                    <a class="page-link" href="#" data-page="${i}">${i}</a>
                </li>
            `;
        } else if (
            i === currentPage - 3 || // 当前页前两个页码
            i === currentPage + 3 // 当前页后两个页码
        ) {
            pagination.innerHTML += `
                <li class="page-item disabled">
                    <span class="page-link">...</span>
                </li>
            `;
        }
    }
    
    // 下一页
    pagination.innerHTML += `
        <li class="page-item ${currentPage === totalPages ? 'disabled' : ''}">
            <a class="page-link" href="#" data-page="${currentPage + 1}">下一页</a>
        </li>
    `;
    
    // 添加页码点击事件
    pagination.querySelectorAll('.page-link').forEach(link => {
        link.addEventListener('click', (e) => {
            e.preventDefault();
            const page = parseInt(e.target.dataset.page);
            if (!isNaN(page) && page !== currentPage) {
                currentPage = page;
                renderTable();
                renderPagination();
            }
        });
    });
}

// Logo预览
document.getElementById('platformLogo').addEventListener('change', function(e) {
    const file = e.target.files[0];
    const preview = document.getElementById('logoPreview');
    if (file) {
        const reader = new FileReader();
        reader.onload = function(e) {
            preview.src = e.target.result;
            preview.classList.remove('d-none');
        };
        reader.readAsDataURL(file);
    } else {
        preview.classList.add('d-none');
        preview.src = '';
    }
});

// 提交新平台
document.getElementById('submitPlatform').addEventListener('click', function() {
    const form = document.getElementById('addPlatformForm');
    if (!form.checkValidity()) {
        form.reportValidity();
        return;
    }

    const formData = new FormData();
    formData.append('name', document.getElementById('platformName').value);
    formData.append('description', document.getElementById('platformDescription').value);
    
    const logoFile = document.getElementById('platformLogo').files[0];
    if (logoFile) {
        formData.append('logo', logoFile);
    }

    axios.post('/api/platform_info/v1/create/', formData, {
        headers: {
            'Content-Type': 'multipart/form-data'
        }
    })
    .then(response => {
        if (response.data.code === 0) {
            showToast('添加平台成功', 'success');
            // 关闭模态框
            const modal = bootstrap.Modal.getInstance(document.getElementById('addPlatformModal'));
            modal.hide();
            // 重置表单
            form.reset();
            document.getElementById('logoPreview').classList.add('d-none');
            document.getElementById('logoPreview').src = '';
            // 刷新平台列表
            getAllPlatforms();
        } else {
            showToast(response.data.message, 'error');
        }
    })
    .catch(error => {
        console.error('添加平台失败:', error);
        showToast('添加平台失败', 'error');
    });
});

// 监听每页显示数量变化
document.getElementById('pageSize').addEventListener('change', (e) => {
    pageSize = parseInt(e.target.value);
    currentPage = 1; // 重置到第一页
    renderTable();
    renderPagination();
});

// 显示更新模态框
function showUpdateModal(platformId, name, description) {
    // 获取当前平台对象
    const platform = allPlatforms.find(p => p.platform_id === platformId);
    document.getElementById('updatePlatformId').value = platformId;
    document.getElementById('updatePlatformName').value = name;
    document.getElementById('updatePlatformDescription').value = description;
    document.getElementById('updatePlatformLogo').value = '';
    // 设置 logo 预览
    const preview = document.getElementById('updateLogoPreview');
    if (platform && platform.logo) {
        preview.src = platform.logo;
        preview.classList.remove('d-none');
        document.getElementById('updateLogoUrl').value = platform.logo;
    } else {
        preview.classList.add('d-none');
        preview.src = '';
        document.getElementById('updateLogoUrl').value = '';
    }
    const modal = new bootstrap.Modal(document.getElementById('updatePlatformModal'));
    modal.show();
}

// Logo预览（更新模态框）
document.getElementById('updatePlatformLogo').addEventListener('change', function(e) {
    const file = e.target.files[0];
    const preview = document.getElementById('updateLogoPreview');
    if (file) {
        const reader = new FileReader();
        reader.onload = function(e) {
            preview.src = e.target.result;
            preview.classList.remove('d-none');
        };
        reader.readAsDataURL(file);
    } else {
        // 未选择新图片，恢复为原logo
        const url = document.getElementById('updateLogoUrl').value;
        if (url) {
            preview.src = url;
            preview.classList.remove('d-none');
        } else {
            preview.classList.add('d-none');
            preview.src = '';
        }
    }
});

// 提交更新
document.getElementById('submitUpdate').addEventListener('click', function() {
    const form = document.getElementById('updatePlatformForm');
    if (!form.checkValidity()) {
        form.reportValidity();
        return;
    }

    const formData = new FormData();
    formData.append('PlatformInfoID', document.getElementById('updatePlatformId').value);
    formData.append('name', document.getElementById('updatePlatformName').value);
    formData.append('description', document.getElementById('updatePlatformDescription').value);
    
    const logoFile = document.getElementById('updatePlatformLogo').files[0];
    if (logoFile) {
        formData.append('logo', logoFile);
    }

    axios.post('/api/platform_info/v1/update/', formData, {
        headers: {
            'Content-Type': 'multipart/form-data'
        }
    })
    .then(response => {
        if (response.data.code === 0) {
            showToast('更新平台成功', 'success');
            // 关闭模态框
            const modal = bootstrap.Modal.getInstance(document.getElementById('updatePlatformModal'));
            modal.hide();
            // 刷新平台列表
            getAllPlatforms();
        } else {
            showToast(response.data.message, 'error');
        }
    })
    .catch(error => {
        console.error('更新平台失败:', error);
        showToast('更新平台失败', 'error');
    });
});

// 页面加载完成后获取平台信息
document.addEventListener('DOMContentLoaded', getAllPlatforms);
</script>
{% endblock %}

{% block nav_left %}
{% include "pc/components/左侧导航栏.html" %}
{% endblock %}

{% block NavBar %}
{% endblock %}

{% include 'pc/公共样式配置/JS总样式.html' %}

{% block footer %}
    {% include "pc/components/Footer.html" %}
{% endblock %}